<?php

namespace App\Http\Controllers\Admin\Dispatch;

use App\Exports\StockExport;
use App\Http\Controllers\Controller;
use App\Imports\StockImport;
use App\Models\dispatch\PurchaseModel;
use App\Models\dispatch\StockModel;
use App\Models\dispatch\MaterialModel;
use App\Models\dispatch\StockRecordModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class Stock extends Controller
{

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $name = $request->input('name', '');
//        $month = $request->input('month', '');

        $query = StockModel::query()->with(['create_admin', 'material'])->whereHas('material');

        if($name){
            $material_id = MaterialModel::where('name', 'like', "%{$name}%")->pluck('id');
            if($material_id){
                $query = $query->whereIn('material_id', $material_id);
            }
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'material_id' => $item->material_id,
                'material_name' => $item->material ? $item->material->name : '',
                'material_code' => $item->material ? $item->material->code : '',
                'material_unit' => $item->material ? $item->material->unit : '',
                'material_limit' => $item->material ? $item->material->limit : '',
                'material_spe' => $item->material ? $item->material->spe : '',
                'material_color' => $item->material ? $item->material->color : '',
//                'month' => $item->month,
//                'start_number' => $item->start_number,
                'stock_number' => $item->stock_number,
//                'purchase_number' => $item->purchase_number,
//                'loss_number' => $item->status == 1 ? $item->loss_number : '',
                'created_at' => $item->created_at->toDateTimeString()
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    /**
     * Notes:更新库存
     * User: xiangzi
     * Date: 2024/9/11
     * Time: 10:58
     * @return \Illuminate\Http\JsonResponse
     */
    public function stock(Request $request, $id) {
        $auth = $request->get('auth');
        $params = $request->all();

        $validator = Validator::make($params, [
            'stock_number' => 'required|numeric'
        ], [
            'stock_number.required' => '请填写当前库存',
            'stock_number.numeric' => '数据类型错误'
        ]);

        if ($validator->fails()) {
            $err = $validator->errors()->first();
            return $this->error($err);
        }

        $model = StockModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        $model->stock_number = $params['stock_number'];
        $model->save();

//        DB::beginTransaction();
//        try {
//            $model->stock_number = $params['stock_number'];
//            $model->loss_number = $model->start_number + $model->purchase_number - $params['stock_number'];
//            $model->status = 1;
//            $model->save();
//
//            $next = new StockModel();
//            $next->material_id = $model->material_id;
//            $next->start_number = $params['stock_number'];
//            $next->month = date('Y-m', strtotime('+1 month'));
//            $next->created_admin_id = $auth->id;
//            $next->save();
//            DB::commit();
//        } catch (\Exception $e) {
//            DB::rollBack();
//            return $this->error($e->getMessage());
//        }

        return $this->success();
    }

    /**
     * Notes:采购记录
     * User: xiangzi
     * Date: 2024/9/27
     * Time: 17:16
     * @return \Illuminate\Http\JsonResponse
     */
    public function record_old(Request $request) {
        $params = $request->all();

        if(!isset($params['material_id'])) {
            return $this->error('物料id不能为空');
        }

        $model = PurchaseModel::where('material_id', $params['material_id'])
            ->where('status', 5)
            ->get();

        $list = $model->map(function($item) {
            $res = [
                'purchase_time' => $item->confirm_time,
                'purchase_number' => $item->purchase_number,
                'file' => json_decode($item->file, true),
            ];
            return $res;
        });

        return $this->success(['list' => $list]);
    }

    /**
     * Notes:出入库记录
     * User: xiangzi
     * Date: 2025/4/24
     * Time: 下午1:58
     * @return \Illuminate\Http\JsonResponse
     */
    public function record(Request $request) {
        $params = $request->all();

        if(!isset($params['material_id'])) {
            return $this->error('物料id不能为空');
        }

        $model = StockRecordModel::with('material')->with('create_admin')
            ->where('material_id', $params['material_id'])
            ->orderBy('id', 'desc')
            ->get();

        $list = $model->map(function($item) {
            $res = [
                'material_name' => $item->material ? $item->material->name : '',
                'type' => $item->type == 1 ? '入库' : '出库',
                'number' => $item->number,
                'user' => $item->user,
                'remark' => $item->remark,
                'created_at' => $item->created_at->toDateTimeString(),
                'create_user' => $item->create_admin ? $item->create_admin->staff->name : ''
            ];
            return $res;
        });

        return $this->success(['list' => $list]);
    }

    /**
     * Notes:出库
     * User: xiangzi
     * Date: 2025/4/24
     * Time: 下午2:02
     * @return \Illuminate\Http\JsonResponse
     */
    public function out(Request $request) {
        $params = $request->all();

        if(!isset($params['data'])) {
            return $this->error('出库数据不能为空');
        }

        DB::beginTransaction();
        try {
            $data = $params['data'];

            foreach ($data as $item){
                $stock = StockModel::where('material_id', $item['material_id'])->first();

                if($stock->stock_number < $item['number']){
                    return $this->error('库存不足');
                }

                $stock->stock_number = $stock->stock_number - $item['number'];
                $stock->save();

                $record = new StockRecordModel();
                $record->material_id = $item['material_id'];
                $record->type = 2;
                $record->number = $item['number'];
                $record->user = $item['user'];
                $record->remark = $item['remarks'];
                $record->created_admin_id = $request->get('auth')->id;
                $record->save();
            }

            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    public function import(Request $request)
    {
        $auth = $request->get('auth');
        $file = $request->file('file');
        if(!$file) {
            return $this->error('请选择文件');
        }

        $import = new StockImport();
        Excel::import($import, $file);


        $res = $import->get_result();

        if(isset($res->error) && $res->error){
            return $this->error(implode(',', $res->error));
        }

        $lines = $res->lines;

        DB::beginTransaction();
        try {
            foreach ($lines as $line){
                $material = MaterialModel::where('name', $line['name'])->first();

                if(!$material){
                    $material  = new MaterialModel();
                }

                $material->type = $line['type'];
                $material->name = $line['name'];
                $material->code = $line['code'];
                $material->unit = $line['unit'];
                $material->spe = $line['spe'];
                $material->model = $line['model'];
                $material->color = $line['color'];
                $material->created_admin_id = $auth->id;
                $material->save();

                $stock = StockModel::where('material_id', $material->id)->first();

                if(!$stock){
                    $stock = new StockModel();
                }

                $stock->material_id = $material->id;
                $stock->stock_number = $line['number'];
                $stock->price = $line['price'];
                $stock->last_month_number = $line['last_month_number'];
                $stock->last_month_amount = $line['last_month_amount'];
                $stock->enter_date = $line['enter_date'];
                $stock->enter_number = $line['enter_number'];
                $stock->enter_amount = $line['enter_amount'];
                $stock->out_date = $line['out_date'];
                $stock->out_number = $line['out_number'];
                $stock->out_amount = $line['out_amount'];
                $stock->save_number = $line['save_number'];
                $stock->save_amount = $line['save_amount'];
//                $stock->remark = $line['remark'];
                $stock->created_admin_id = $auth->id;
                $stock->save();
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return  $this->success();
    }

    public function export(Request $request)
    {
        $ids = $request->input('ids', []);
        if(empty($ids)){
            return $this->error('请选择要导出的数据');
        }

        $query = StockModel::with('material');
        $query->whereIn('id', $ids);
        $items = $query
            ->orderBy('id', 'desc')
            ->get();


        $list = $items->map(function($item) {
            $res = [
                'type' => $item->material->type ?? '',
                'code' => $item->material->code ?? '',
                'name' => $item->material->name ?? '',
                'spe' => $item->material->spe ?? '',
                'model' => $item->material->model ?? '',
                'color' => $item->material->color ?? '',
                'unit' => $item->material->unit ?? '',
                'number' => $item->stock_number,
                'price' => $item->price,
                'last_month_number' => $item->last_month_number,
                'last_month_amount' => $item->last_month_amount,
                'enter_date' => $item->enter_date,
                'enter_number' => $item->enter_number,
                'enter_amount' => $item->enter_amount,
                'out_date' => $item->out_date,
                'out_number' => $item->out_number,
                'out_amount' => $item->out_amount,
                'save_number' => $item->save_number,
                'save_amount' => $item->save_amount,
            ];

            return $res;
        });

        $file_name = '物料库存-'.date('Ymd').'.xlsx';

        return Excel::download(new StockExport($list), $file_name);
    }

}
